package com.lottery.common.utils;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.lottery.common.model.JPush;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Slf4j
@Service
public class JPushUtils {
    @Autowired
    private JPush j;
    private static JPush jPush;


    @PostConstruct
    public void init() {
        log.info("init JPushUtils");
//        memberMapper= this.mMapper;
        jPush= this.j;
    }
    public static void pushMsg(NutMap nutMap){

        //time_to_live 字段如果为 0 ，表示该消息不保存离线，即如果用户当前不在线，
        // 则用户就会一直收不到该消息。time_to_live 大于 0 时会保留指定时长的离线消息时间,离线消息默认的保留时长是 1 天。
        ClientConfig config = ClientConfig.getInstance();
        //重发的次数
        config.setMaxRetryTimes(3);
        config.setConnectionTimeout(10 * 1000);    // 10 seconds
        config.setTimeToLive(5);

        JPushClient jpushClient = new JPushClient(jPush.getMasterSecret(), jPush.getAppKey(), null, config);

        // For push, all you need do is to build PushPayload object.

        PushPayload payload = null;
        if (nutMap.get("rid")!=null){
            payload=initPushPayloadAddRId(nutMap);
        }else if (nutMap.get("tag")!=null){
            payload=initPushPayloadAddTag(nutMap);
        }else{
            payload=initPushPayload(nutMap);
        }
        if (payload==null){
            log.error("____PushPayload 初始化失败 nutMap is {}", JSON.toJSONString(nutMap));
            return;
        }
        try {
            PushResult result = jpushClient.sendPush(payload);
            log.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            log.error("Connection error, should retry later {}", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            log.error("Should review the error, and fix the request", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        } finally {
            jpushClient.close();
        }
    }



    public static PushPayload initPushPayload(NutMap nutMap) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder().addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(nutMap.get("alert")).setTitle(nutMap.getString("title")).build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(nutMap.get("alert")).addExtra("title",nutMap.getString("title")).build())
                        .build())
                .build();
    }

    public static PushPayload initPushPayloadAddRId(NutMap nutMap) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(nutMap.getString("rid")))
                .setNotification(Notification.newBuilder().addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(nutMap.get("alert")).setTitle(nutMap.getString("title")).build())
                        .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(nutMap.get("alert")).addExtra("title",nutMap.getString("title")).build())
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent("")
//                        .addExtra("from", "JPush")
                        .build())
                .build();
    }

    public static PushPayload initPushPayloadAddRIds(NutMap nutMap) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(nutMap.getArray("rids",String.class)))
                .setMessage(Message.newBuilder()
                        .setMsgContent("")
//                        .addExtra("from", "JPush")
                        .build())
                .build();
    }

    public static PushPayload initPushPayloadAddTag(NutMap nutMap) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag(nutMap.getString("tag")))
                .setNotification(Notification.newBuilder().addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(nutMap.get("alert")).setTitle(nutMap.getString("title")).build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(nutMap.get("alert")).addExtra("title",nutMap.getString("title")).build())
                        .build())
                .build();
    }


    public static PushPayload initPushPayloadMsg(NutMap nutMap) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.all())
                .setMessage(Message.newBuilder()
                        .setMsgContent(nutMap.getString("content"))
                        .addExtra("img",nutMap.getString("img"))
                        .build())
                .build();
    }
}
